package demo08;

/**
 * @author JYH
 * @version 1.0
 * @date 2022/11/1 16:47
 */
public class CardTest {
    public static void main(String[] args) {
        BankCard bankCard=new BankCard();
        Boy boy=new Boy(bankCard);
        Girl girl=new Girl(bankCard);
        boy.setName("男孩");
        girl.setName("女孩");
        boy.start();
        girl.start();
    }
}
class BankCard{
    private double balance;
    private boolean flag=false;
    public synchronized void save(double money){
        //卡中有钱无需存钱
        if(flag==true){
            try {
                //释放锁并进入等待队列
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        balance=balance+money;
        System.out.println(Thread.currentThread().getName()+"存入了"+money+"元，卡中余额:"+balance);
        flag=true;
        //唤醒等待队列中的线程
        notify();
    }
    public synchronized void take(double money){
        System.out.println(Thread.currentThread().getName());
        if(flag==false){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        balance=balance-money;
        System.out.println(Thread.currentThread().getName()+"取出了"+money+"元，卡中余额:"+balance);
        flag=false;
        notify();
    }

}
class Boy extends Thread{
    private BankCard bankCard;
    public Boy(BankCard bankCard){
        this.bankCard=bankCard;
    }

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            bankCard.save(1000);
        }
    }
}
class Girl extends Thread{
    private BankCard bankCard;
    public Girl(BankCard bankCard){
        this.bankCard=bankCard;
    }
    @Override
    public void run() {
        for (int i = 0; i <10 ; i++) {
            bankCard.take(1000);
        }
    }


}